<template>
  <div class="inventory-duty-form">
    <el-form ref="myform" v-loading="loading" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-divider content-position="left">基本信息</el-divider>
      <el-form-item label="盘点计划" prop="inventoryPlanName">
        <el-input v-model="formItem.inventoryPlanName" disabled />
      </el-form-item>
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="formItem.name" placeholder="请输入任务名称" />
      </el-form-item>
      <el-form-item label="部门" prop="orgCodes">
        <treeselect
          key="orgTreeSelect"
          v-model="formItem.orgCodes"
          :multiple="false"
          :options="availableOganizationTree"
          placeholder="请选择部门"
          value-consists-of="ALL_WITH_INDETERMINATE"
          @select="selcetOrg"
          @input="clearOrg"
        />
      </el-form-item>
      <el-divider content-position="left" />
      <el-table
        key="departmentTable"
        :loading="false"
        :data="tasksByDepartment"
      >
        <el-table-column v-for="column in tasksByDepartmentColumns" :key="column.key" :label="column.title" :prop="column.key" :width="column.width" :sortable="column.sortable">
          <template slot-scope="scope">
            <column-render :render="column.render" :row="scope.row" :column="column" />
          </template>
        </el-table-column>
        <el-table-column label="位置">
          <template slot-scope="scope">
            <treeselect
              key="locationTreeForSelectAssets"
              v-model="scope.row.locationCodes"
              :multiple="true"
              :options="availableLocationTree"
              value-consists-of="LEAF_PRIORITY"
              @input="inputChange(scope.row, 'no')"
            />
          </template>
        </el-table-column>
        <!-- ********************************************************************************************* -->
        <el-table-column v-if="$attrs.belongs == 'kj'" label="资产类型">
          <template slot-scope="scope">
            <treeselect
              key="locationTreeForSelectAsset1s"
              v-model="formItem.assetTypeCodes"
              :multiple="true"
              :options="typeOptions"
              value-consists-of="LEAF_PRIORITY"
              @input="inputChange(scope.row, formItem.assetTypeCodes)"
            />
          </template>
        </el-table-column>
        <!-- ********************************************************************************************* -->
        <el-table-column label="责任人" :width="200">
          <template slot-scope="scope">
            <el-select v-if="scope.row.count > 0" v-model="scope.row.account" size="mini" clearable placeholder="请选择责任人" @change="onDepartmentAccoiuntChange(scope.row)">
              <el-option v-for="item in scope.row.availableUsers" :key="item.username" :label="item.name" :value="item.username" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="查看资产" :width="200">
          <template slot-scope="scope">
            <el-button size="mini" icon="el-icon-plus" @click="onOpenAssetPage(scope.row)">查看资产</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <ViewDialog v-if="assetSelDialogFormVisible" width="80%" title="查看盘点资产" :show="assetSelDialogFormVisible" :append-to-body="true" @on-cancel="onCloseAssetDialog">
      <el-tabs v-model="activeName">
        <el-tab-pane label="固定资产" name="first">
          <FixedAssetTable v-if="activeName === 'first'" ref="assetTable" :for-selection="true" :multiple-selected="true" :belongs="$attrs.belongs" categories="1" :management-org-code="selectedOrgCode" :org-search-show="false" :location-arr="selectedLocationCodeArr" :type-arr="selectedassetTypeCodeArr" />
        </el-tab-pane>
        <el-tab-pane label="低值易耗品" name="second">
          <FixedAssetTable v-if="activeName === 'second'" ref="assetTable" :for-selection="true" :multiple-selected="true" :belongs="$attrs.belongs" categories="2" :management-org-code="selectedOrgCode" :org-search-show="false" :location-arr="selectedLocationCodeArr" :type-arr="selectedassetTypeCodeArr" />
        </el-tab-pane>
      </el-tabs>
    </ViewDialog>
  </div>
</template>

<script>
import { detail as planDetail } from '@neu/dcam-ui/api/inventoryPlan'
import {
  create,
  update,
  detail
} from '@neu/dcam-ui/api/inventoryDuty'
import ViewDialog from '@neu/biz-core/components/ViewDialog'
import { tree } from '@neu/dcam-ui/api/location'
import { tree as organizationsTree } from '@neu/auth-ui/api/organization'
import FixedAssetTable from '@neu/dcam-ui/views/fixedAsset/tables'
import { count as fetchOrgAssetCount } from '@neu/dcam-ui/api/fixedAsset'
import { listByOrg as getUserListByOrgCode } from '@neu/auth-ui/api/user'
import { INVENTORY_DUTY_TYPE_LIST } from '@neu/dcam-ui/utils/constants'
import { tree as assetTypeTree } from '@neu/dcam-ui/api/assetType'
// 定义一个表单原始项，原始设计时，可以一次设置多个部门，生成多个任务
// 目前的实现是一次只能设置一个部门，所有原来很多的数组存储结构仍然保留，但只存一个值
const formItem = {
  // 任务名
  name: '',
  status: 'created',
  // 计划ID
  inventoryPlanId: '',
  // 计划名称
  inventoryPlanName: '',
  // 部门编码列表（现在只存一个值）
  orgCodes: null,
  // 部门名称列表（现在只存一个值）
  orgNames: [],
  /** 资产分类 */
  typeOptions: [],
  // 盘点负责人编码列表（现在只存一个值）
  accountCodes: [],
  // 盘点负责人名字列表（现在只存一个值）
  accountNames: [],
  // 部门盘点任务中，资产位置的限定条件（可以多选）
  assetTypeCodes: [],
  // 部门盘点任务中，资产位置的限定条件（可以多选）
  locationCodes: [],
  type: 'department',
  differentTypes: 'ZH'
}
export default {
  name: 'InventoryPlanEditForm',
  components: {
    ViewDialog,
    FixedAssetTable
  },
  props: {
    planId: {
      required: true,
      type: Number,
      default: -1
    },
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      loading: false,
      // 编辑的表单内容
      formItem: {
        ...formItem
      },
      // 位置树数据
      availableLocationTree: [],
      // 组织树数据
      availableOganizationTree: [],
      // 表单验证规则
      rules: {
        name: [{
          required: true,
          message: '任务名称不能为空',
          trigger: 'blur'
        },
        {
          validator: function(rule, value, callback) {
            if (value.length > 100) {
              callback(new Error('最多可输入100个字符'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }],
        inventoryPlanId: [{
          required: true,
          message: '盘点计划不能为空',
          trigger: 'change'
        }],
        orgCodes: [{
          required: true,
          message: '部门不能为空',
          trigger: 'blur'
        }]
      },
      /** 是否显示资产选择对话框 */
      assetSelDialogFormVisible: false,
      /** 按部门创建的任务项数据。当前一次只支持设置一个部门的任务 */
      tasksByDepartment: [],
      /** 按部门创建的任务表格定义 */
      tasksByDepartmentColumns: [
        { title: '部门', key: 'orgName', width: '180' },
        { title: '资产数量', key: 'count', width: '120',
          render: (h, params) => { // 查看功能
            if (!params.row.count) {
              return h('span', {
                style: {
                  color: 'red'
                }
              }, params.row.count)
            } else {
              return h('span', params.row.count)
            }
          }
        }
      ],
      INVENTORY_DUTY_TYPE_LIST,
      activeName: 'first'
    }
  },
  computed: {
    // 将组织树扁平化，方便查找
    flatOrgs: function() {
      const list = []
      recur(this.availableOganizationTree)
      // 递归
      function recur(children) {
        for (let i = 0; i < children.length; i++) {
          list.push(children[i])
          if (children[i].children) {
            recur(children[i].children)
          }
        }
      }
      return list
    },
    // 查看任务资产时，传递选中的部门代码
    selectedOrgCode: function() {
      return this.tasksByDepartment.length > 0 ? this.tasksByDepartment[0].orgCode : ''
    },
    // 查看任务资产时，传递选中的位置编码
    selectedLocationCodeArr: function() {
      return this.tasksByDepartment.length > 0 ? this.tasksByDepartment[0].locationCodes : []
    },
    // 查看任务资产时，传递选中的位置编码
    selectedassetTypeCodeArr: function() {
      return this.formItem.assetTypeCodes
    }
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler(newVal, oldVal) {
        this.fetch()
      },
      immediate: true
    }
  },
  created() {
    // 获取位置数据
    tree(this.$attrs.belongs).then(response => {
      this.availableLocationTree = response.data
    })
    assetTypeTree(this.$attrs.belongs, '2').then(res => {
      this.typeOptions = res.data
      // this.flattenTypeTreeData = this.flattenTreeDataClosure(res.data)
    })
  },
  methods: {
    // 初始化表单数据
    fetch: async function() {
      const result = await organizationsTree(this.$attrs.belongs)
      this.availableOganizationTree = [result.data]
      if (this.id !== -1) {
        // 获取任务详情数据
        detail(this.id).then(response => {
          // 综合一下初始化表单内容
          this.initForm({
            id: response.data.inventoryPlanId,
            name: response.data.inventoryPlanName
          }, response.data)

          // 根据任务关联的部门，构造回显任务部门信息的基础数据
          this.formItem.orgCodes.forEach(org => {
            const o = this.findOrgInfo(org)
            this.selcetOrg(o, 'no')
          })
        })
      } else {
        if (this.planId > -1) {
          // 新建任务
          planDetail(this.planId).then(planInfo => {
            this.initForm(planInfo.data, formItem)
          })
        }
      }
    },
    // 初始化表单数据
    initForm(planInfo, taskInfo) {
      this.formItem = {
        ...taskInfo,
        inventoryPlanId: planInfo.id,
        inventoryPlanName: planInfo.name
      }
      console.log(this.formItem)
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      if (this.formItem.type === 'department') {
        if (this.tasksByDepartment.filter(task => task.count > 0).length === 0) {
          this.$message({
            type: 'warning',
            message: '所选部门下都没有关联资产'
          })
          return new Promise(resolve => {
            resolve(false)
          })
        } else {
          const task = this.tasksByDepartment[0]
          this.formItem.orgCodes = [task.orgCode]
          this.formItem.orgNames = [task.orgName]
          // this.formItem.accountCodes = [task.account]
          // this.formItem.accountNames = [task.accountName]
          // this.formItem.assetTypeCodes = task.assetTypeCodes
          this.formItem.locationCodes = task.locationCodes
          this.formItem.account = task.account
          this.formItem.userName = task.accountName
        }
      }
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.myform.validate((valid) => {
          if (valid) {
            if (updated) {
              resolve(update(this.id, this.formItem))
            } else {
              resolve(create(this.formItem))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    // 选择准备要盘点的部门
    selcetOrg(value, val) {
      if (!value) {
        return
      }
      this.tasksByDepartment = []
      this.formItem.orgNames.push(value.title)
      // 构造列表任务项
      const taskInfo = {
        orgCode: value.code,
        orgName: value.title
      }
      const query = {
        s_managementOrgCode: value.code,
        s_belongs: this.$attrs.belongs
      }

      if (val === 'no' && this.formItem.locationCodes && this.formItem.locationCodes.length > 0) {
        taskInfo.locationCodes = this.formItem.locationCodes
      }

      if (taskInfo.locationCodes && taskInfo.locationCodes.length > 0) {
        query.s_locationArr = taskInfo.locationCodes.join(',')
      }
      // 选择完部门后，实时查一下部门下资产的数量
      fetchOrgAssetCount(query).then(res1 => {
        // 部门下资产数量
        taskInfo.count = res1.data

        if (taskInfo.count > 0) {
          // 如果部门下存在资产，在查一下部门下的用户
          getUserListByOrgCode(value.code).then(res => {
            // 部门下所有人员
            taskInfo.availableUsers = res.data || res.data.map(it => {
              return {
                code: it.username,
                name: it.name
              }
            })
            const oldUser = taskInfo.availableUsers.filter(user => user.username === this.formItem.account)
            if (oldUser.length > 0) {
              taskInfo.account = oldUser[0].username
              taskInfo.accountName = oldUser[0].name
            } else {
              taskInfo.availableUsers.filter(user => {
                // 科技公司的【部门资产专管员】、总行的【部门资产管理员】，两个角色默认是任务的负责人
                const assetAdminRole = user.roles.find(role => role.code === 'kjDeptAssetAdmin' || role.code === 'slDeptAssetAdmin')
                if (assetAdminRole) {
                  taskInfo.account = user.username
                  taskInfo.accountName = user.name
                }
              })
            }
            this.tasksByDepartment.push(taskInfo)
          })
        } else {
          this.tasksByDepartment.push(taskInfo)
        }
        if (val !== 'no') {
          this.formItem.assetTypeCodes = []
        }
        console.log(this.tasksByDepartment)
        console.log(taskInfo)
      })
    },
    // 清空部门选项
    clearOrg(value) {
      if (!value) {
        this.formItem.orgCodes = null
        this.formItem.orgNames = []
        this.formItem.accountCodes = []
        this.formItem.accountNames = []
        this.formItem.locationCodes = []
        this.formItem.assetTypeCodes = []
        this.tasksByDepartment = []
      }
    },
    /** 重置表单 */
    reset() {
      this.$refs.myform.resetFields()
      this.formItem.userName = ''
      // this.formItem = { ...formItem }
    },
    // 关闭资源查看对话框
    onCloseAssetDialog() {
      this.assetSelDialogFormVisible = false
    },
    // 查看任务关联资产。打开资产对话框，并传递限定条件
    onOpenAssetPage(row) {
      this.assetSelDialogFormVisible = true
    },
    // 根据编码查找部门信息(因为前段拿到的是组织树，所以查找稍微麻烦些)
    findOrgInfo(code) {
      return this.flatOrgs.find(it => it.code === code)
    },
    // 改变盘点任务责任人
    onDepartmentAccoiuntChange(taskInfo) {
      const user = taskInfo.availableUsers.find(it => it.username === taskInfo.account)
      const listItem = this.tasksByDepartment.find(it => it.orgCode === taskInfo.orgCode)
      if (user) {
        listItem.accountName = user.name
      } else {
        listItem.accountName = ''
      }
    },
    inputChange(row, typeList) {
      const query = { s_managementOrgCode: row.orgCode }
      if (row.locationCodes.length > 0) {
        query.s_locationArr = row.locationCodes.join(',')
      }
      if (typeList === 'no') {
        this.formItem.assetTypeCodes = []
      }
      if (typeList !== 'no' && typeList.length > 0) {
        query.s_typeCodesArr = typeList.join(',')
      }
      fetchOrgAssetCount(query).then(res1 => {
        row.count = res1.data
      })
    }
  }
}
</script>

<style lang="scss">
  .inventory-duty-form {
    .el-table{
      overflow: visible;
    }
    .el-table .cell{
      overflow: visible;
    }
    .el-table__body-wrapper{
      overflow: visible;
    }
  }
</style>
